package com.breeze.counttime

import org.gradle.BuildListener
import org.gradle.BuildResult
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.execution.TaskExecutionListener
import org.gradle.api.initialization.Settings
import org.gradle.api.invocation.Gradle
import org.gradle.api.tasks.TaskState

class CountTimePlugin implements Plugin<Project> {
    // 用来记录 task 的执行时长等信息
    Map<String, TaskExecTimeInfo> mTimeCostMap = new HashMap<>()
    // 用来按顺序记录执行的 task 名称
    List<String> mTaskPathList = new ArrayList<>()

    @Override
    void apply(Project project) {
        CountTimeExtension countTimeExtension = project.getExtensions().create("counttime", CountTimeExtension)
        project.getGradle().addListener(new TaskExecutionListener() {
            @Override
            void beforeExecute(Task task) {
                def info = new TaskExecTimeInfo()
                info.start = System.currentTimeMillis()
                info.path = task.getPath()
                mTimeCostMap.put(info.path, info)
                mTaskPathList.add(info.path)
            }

            @Override
            void afterExecute(Task task, TaskState taskState) {
                def info = mTimeCostMap.get(task.getPath())
                info.end = System.currentTimeMillis()
                info.total = info.end - info.start
            }
        })
        project.getGradle().addBuildListener(new BuildListener() {
            @Override
            void buildStarted(Gradle gradle) {

            }

            @Override
            void settingsEvaluated(Settings settings) {

            }

            @Override
            void projectsLoaded(Gradle gradle) {

            }

            @Override
            void projectsEvaluated(Gradle gradle) {

            }

            @Override
            void buildFinished(BuildResult buildResult) {
                println '=============count time begin============='
                if (countTimeExtension.sort) {
                    Collections.sort(mTaskPathList, new Comparator<String>() {
                        @Override
                        int compare(String t, String t1) {
                            // 降序排列
                            return mTimeCostMap.get(t1).total - mTimeCostMap.get(t).total
                        }
                    })
                }
                mTaskPathList.each { String path ->
                    def info = mTimeCostMap.get(path)
                    if (info.total > countTimeExtension.threshold) {
                        println "> Task ${path} [${info.total}ms]"
                    }
                }
                println '=============count time end============='
            }
        })
    }
    // 关于 task 的执行信息
    class TaskExecTimeInfo {
        long total      // task执行总时长
        long start      // task执行开始时间
        long end        // task执行结束时间
        String path
    }
}
